import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { showNotify } from 'vant';
import userinfo from '@/store/userinfo';
import i18n from '@/const/lang';

const BASE_PREFIX = import.meta.env.VITE_API_BASEURL;

// 创建实例
const axiosInstance: AxiosInstance = axios.create({
  // 前缀
  baseURL: BASE_PREFIX,
  // 超时
  timeout: 1000 * 60,
  // 请求头
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // TODO 在这里可以加上想要在请求发送前处理的逻辑
    // TODO 比如 loading 等
    const currentUser:any = userinfo().getUserinfo;
    // 设置 access_token
    if(currentUser && currentUser?.token){
      config.headers!.token = currentUser?.token;
    }else{
      Reflect.deleteProperty(config.headers!, "Authorization");
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  async (response: AxiosResponse) => {
    // 如果是字符串则解析字符串
    const piniaUserinfo:any = userinfo();
    if (response.status === 200) {
      if(response.data?.code === 401 || response.data?.code === 403){
        piniaUserinfo.logout();
      } else if(response?.data?.code === 500){
        showNotify({
          type: 'danger',
          message: response?.data?.msg,
        });
        return response.data;
      }else{
        return response.data;
      }
    }
    return response;
  },
  (error: AxiosError) => {
    const { response } = error;
    const piniaUserinfo:any = userinfo();
    if (response) {
      if(response.data?.code === 401 || response.data?.code === 403){
        showNotify({
          type: 'danger',
          message: response?.data?.msg,
        });
        piniaUserinfo.logout();
      }
    }
    showNotify({
      type: 'warning',
      message: (i18n.global as any).t('lang.net.error'),
    });
    return Promise.reject(error);
  },
);

const service = {
  get<T = unknown>(url: string, data?: object): Promise<T> {
    return axiosInstance.get(url, { params: data });
  },

  post<T = unknown>(url: string, data?: object): Promise<T> {
    return axiosInstance.post(url, data);
  },

  put<T = unknown>(url: string, data?: object): Promise<T> {
    return axiosInstance.put(url, data);
  },

  delete<T = unknown>(url: string, data?: object): Promise<T> {
    return axiosInstance.delete(url, data);
  },

  upload: (url: string, file: FormData | File) =>
    axiosInstance.post(url, file, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }),
};

export default service;
